/*
 *  Class name: IDGenerator.java
 *  Version: 1.0
 *  Date: 3.6.2014
 */
package cz.muni.fi.pv168.addressbook.entities.xml;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.ToLongFunction;

/**
 *
 * @author Michal Ďuriš
 */
public class IDGenerator {

    private AtomicLong id;

    public IDGenerator() {
        id = new AtomicLong(1);
    }

    public IDGenerator(long initialValue) {
        id = new AtomicLong(initialValue);
    }

    public void setInitialValue(long initialValue) {
        id.set(initialValue);
    }

    public Long getUniqueID() {
        return id.getAndIncrement();
    }

    public <T> void setInitialValue(List<T> list, ToLongFunction<T> idFunction) {

        if (list != null && !list.isEmpty()) {

            List<T> listCopy = new ArrayList<>(list);

            Collections.sort(listCopy, Comparator.comparingLong(idFunction));

            id
                    .set((idFunction.applyAsLong(listCopy.get(
                          (listCopy.size() - 1))) + 1));
        }
    }
}
